package com.weishi.project.speedometer.domain;

import cn.hutool.json.JSONUtil;
import com.weishi.common.utils.DateUtils;
import com.weishi.common.utils.GPSUtil;
import com.weishi.framework.config.BeanContext;
import com.weishi.project.speedometer.service.IMantianxingService;
import com.weishi.project.speedometer.vo.EqmDataVo;
import com.weishi.project.speedometer.vo.MantianxingGpsVo;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.logging.Logger;

public class SimpleMqttCallBack  implements MqttCallback {

    private IMantianxingService mantianxingService;

    Logger logger = Logger.getLogger("Mqtt");

    public SimpleMqttCallBack(){
        this.mantianxingService = BeanContext.getApplicationContext().getBean(IMantianxingService.class);
    }

    public void connectionLost(Throwable throwable) {
        logger.info("Connection to MQTT broker lost!");
    }

    public void messageArrived(String s, MqttMessage mqttMessage){
        String message = new String(mqttMessage.getPayload());
        logger.info(message);
        try {
            EqmDataVo eqmDataVo = JSONUtil.toBean(message, EqmDataVo.class);
            MantianxingGpsVo vo = new MantianxingGpsVo();
            vo.setDeviceId("1314");
            vo.setSpeed(eqmDataVo.getVelocity());
            vo.setB(getDegreeString(eqmDataVo.getB()));
            vo.setL(getDegreeString(eqmDataVo.getL()));
            vo.setTimeTimp(System.currentTimeMillis());
            vo.setLocalTime(DateUtils.getStringTime(eqmDataVo.getLocaleTime()));
            vo.setHrms(eqmDataVo.getHRms());
            vo.setXrms(eqmDataVo.getXRms());
            vo.setYrms(eqmDataVo.getYRms());
            vo.setQuality(eqmDataVo.getQuality());
            vo.setSolutionUsedSats(eqmDataVo.getSolutionUsedSats());
            mantianxingService.addTempList(vo);
            logger.info(vo.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
    }

    /**
     * 经纬度转成度
     * @param radian
     * @return
     */
    public static Double getDegreeString(double radian) {
        int degree = 0;
        double minute = 0;
        double second = 0;

        try {
            double d = Math.toDegrees(radian);
            degree = (int)d;
            minute = (d - degree) * 60;
            second = (minute - (int)minute) * 60;
        } catch (Exception e) {
            e.printStackTrace();
        }
        String gpsTemp = String.format("%1$s ° %2$s ′ %3$.4f ″", degree, (int)minute, second);
        return GPSUtil.Dms2D(gpsTemp);
    }
}
